//
//  ClubDetailTableViewController.swift
//  约健
//
//  Created by tyh on 2017/10/2.
//  Copyright © 2017年 tyh. All rights reserved.
//

import UIKit

class ClubDetailTableViewController: UITableViewController {
    
    var Club:ClubModel!
    var turebarbtnItem:UIBarButtonItem!
    var videosList = NSArray()
    var courseList = NSArray()
    var teacherList = NSArray()
    var rightBtn:UIButton = UIButton.init()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = Club.club_name! as String
        automaticallyAdjustsScrollViewInsets = false
        rightBtn.sizeToFit()
        rightBtn.addTarget(self, action: #selector(Ifcollect), for: UIControlEvents.touchUpInside)
        turebarbtnItem = UIBarButtonItem.init(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = turebarbtnItem
        CreatFootView()
        getVideo()
        getTeacher()
        getCourse()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 5
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if section == 0{
        return 2
        }else{
            return 1
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        if user_id != "-1"{
            self.isexits()
        }else{
            self.rightBtn.setImage(UIImage.init(named: "buzai.png"), for: .normal)
        }
       
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var basecell = UITableViewCell()
        
        if indexPath.section == 0 && indexPath.row == 0{
            let cell = DetailHeadTableViewCell.creatCell(tableView)
           
            let imageStr = "http://172.24.10.175/workout/Uploads/" + (Club.thumb! as String)
            let imageUrl = URL(string: imageStr)
            let data = try! Data(contentsOf: imageUrl!)
            let image = UIImage(data: data)
            cell.Pic.image = image
            cell.Address.text = "地址:\(Club.province_name!)\(Club.city_name!)\(Club.district_name!)"
            
            basecell = cell
        }
        else if indexPath.section == 0 && indexPath.row == 1{
            let cell:TextTableViewCell = tableView.dequeueReusableCell(withIdentifier: "ClubTextCell", for: indexPath) as! TextTableViewCell
            cell.TextName.text = Club.club_name! as String
            cell.TextContent.text = Club.introduction! as String
            basecell = cell
        }else if indexPath.section == 1{
           
            
            if videosList.count != 0{
                let cell:CourseVideoTableViewCell = tableView.dequeueReusableCell(withIdentifier: "videocell", for: indexPath) as! CourseVideoTableViewCell
                
                
                cell.number = videosList.count
                cell.TT.text = "相关视频"
                for i in 0..<videosList.count{
                    let model = videosList[i] as! ClubVideoModel
                    let imageStr = "http://172.24.10.175/workout/Uploads/" + (model.thumb! as String)
                    let imageUrl = URL(string: imageStr)
                    let data = try! Data(contentsOf: imageUrl!)
                    let image = UIImage(data: data)
                    (cell.imageViews[i] as! SingleView).pic.image = image
                    (cell.imageViews[i] as! SingleView).Tittle.text = model.name! as String
                    (cell.imageViews[i] as! SingleView).Btn.tag = i
                    (cell.imageViews[i] as! SingleView).Btn.addTarget(self, action: #selector(PlayVideo), for: .touchUpInside)
                }
                    basecell = cell
            }
                else{
                    let cell = NoDataTableViewCell.creatCell(tableView)
                
                   cell.JieShiText.text = "暂无相关视频！！"
                   cell.Pic.image = UIImage(named: "没有数据.png")
                   basecell = cell
                
                
            }
        

            
        }else if indexPath.section == 2{
         
            let cell = AttentionTableViewCell.creatCell(tableView)
            cell.TakeText.text = Club.equipsuggest! as String
            cell.Time.text = Club.open_time! as String
            cell.Tele.text = Club.club_tel! as String
            basecell = cell
        }
        else if indexPath.section == 3{
            if teacherList.count != 0{
                let cell:CourseVideoTableViewCell = tableView.dequeueReusableCell(withIdentifier: "videocell", for: indexPath) as! CourseVideoTableViewCell
                
                
                cell.number = teacherList.count
                cell.TT.text = "相关教师"
                for i in 0..<teacherList.count{
                    let model = teacherList[i] as! ClubClubteacherModel
                    let imageStr = "http://172.24.10.175/workout/Uploads/" + (model.thumb! as String)
                    let imageUrl = URL(string: imageStr)
                    let data = try! Data(contentsOf: imageUrl!)
                    let image = UIImage(data: data)
                    (cell.imageViews[i] as! SingleView).pic.image = image
                    (cell.imageViews[i] as! SingleView).Tittle.text = model.name! as String
                    (cell.imageViews[i] as! SingleView).Btn.tag = i
                    (cell.imageViews[i] as! SingleView).Btn.addTarget(self, action: #selector(ToTeacherDetail), for: .touchUpInside)
                }
                basecell = cell
            }
            else{
                let cell = NoDataTableViewCell.creatCell(tableView)
                
                cell.JieShiText.text = "暂无相关教师！！"
                cell.Pic.image = UIImage(named: "没有数据.png")
                basecell = cell
                
                
            }

            
        }
        else {
            if courseList.count != 0{
                let cell:CourseVideoTableViewCell = tableView.dequeueReusableCell(withIdentifier: "videocell", for: indexPath) as! CourseVideoTableViewCell
                
                
                cell.number = courseList.count
                cell.TT.text = "相关课程"
                for i in 0..<courseList.count{
                    let model = courseList[i] as! ClubcourseModel
                    let imageStr = "http://172.24.10.175/workout/Uploads/" + (model.thumb! as String)
                    let imageUrl = URL(string: imageStr)
                    let data = try! Data(contentsOf: imageUrl!)
                    let image = UIImage(data: data)
                    (cell.imageViews[i] as! SingleView).pic.image = image
                    (cell.imageViews[i] as! SingleView).Tittle.text = model.course_name! as String
                    (cell.imageViews[i] as! SingleView).Btn.tag = i
                    (cell.imageViews[i] as! SingleView).Btn.addTarget(self, action: #selector(ToCourseDetail), for: .touchUpInside)
                }
                basecell = cell
            }
            else{
                let cell = NoDataTableViewCell.creatCell(tableView)
                
                cell.JieShiText.text = "暂无相关课程！！"
                cell.Pic.image = UIImage(named: "没有数据.png")
                basecell = cell
                
                
            }

            
        }/*
        else{
            let cell:AddClubTableViewCell = tableView.dequeueReusableCell(withIdentifier: "AddCell", for: indexPath) as! AddClubTableViewCell
            cell.Add.addTarget(self, action: #selector(AddClub), for: .touchUpInside)
            basecell = cell
            
        }*/
        
        

        basecell.selectionStyle = UITableViewCellSelectionStyle.none

        return basecell
    }
    
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 && indexPath.row == 0{
            return UIScreen.main.bounds.height * 0.3
        }else if indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 3 || indexPath.section == 4{
            return UIScreen.main.bounds.height * 0.2
        }
        else{
            return UIScreen.main.bounds.height * 0.1
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
     
            return 8
   
    }
    

   
    func AddClub(){
        if user_id == "-1"{
            let loginview = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginView")
            self.present(loginview, animated: true, completion: nil)
        }else{
            let parameters:NSDictionary = ["club_id":Club.id!,"userid":user_id,"SessionID":sessionID,"mod":"clubmember"]
            NetWorkMngTool.sharedNetworkMngtool().Network_AddClub(parameters, view: self.view) {(success) in
              if success == "1"{
                print("success!")
                               }
                                                                                                }
             }
                 }
    func Ifcollect(){
        if user_id == "-1"{
            let loginview = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginView")
            self.present(loginview, animated: true, completion: nil)
        }else{
            let parameters = ["mod":"clubfans", "SessionID":sessionID, "club_id":Club.id!,"user_id":user_id,"fans_type":1] as NSDictionary
            NetWorkMngTool.sharedNetworkMngtool().Network_FansForClub(parameters, view: self.view) {(success) in
                if success == "1"{
                    print("success")
             self.isexits()
                }
        
        }
    }
    }
    func isexits(){
        let parameters = ["mod":"fans", "fan_id":Club.id!,"user_id":user_id,"fans_type":1] as NSDictionary
        NetWorkMngTool.sharedNetworkMngtool().Network_IsExits(parameters, view: self.view) {(success) in
            if success == "1"{
                DispatchQueue.main.async {
             self.rightBtn.setImage(UIImage.init(named: "zai.png"), for: .normal)
                }
            }else if success == "0"{
                DispatchQueue.main.async {
             self.rightBtn.setImage(UIImage.init(named: "buzai.png"), for: .normal)
                }
            }
        }
        
    }
    func getVideo(){
        let parameters = ["mod":"club","SessionID":"2ul9sj8vlfofj122e1s98048k2","id":Club.id,"map":"Clubvideo","related":1] as NSDictionary
        NetWorkMngTool.sharedNetworkMngtool().Network_GetClubVideoList(parameters, view: self.view){(videoList) in
            self.videosList = videoList
            self.tableView.reloadData()
        }

    }
    func getTeacher(){
        let parameters = ["mod":"club","SessionID":"2ul9sj8vlfofj122e1s98048k2","id":Club.id,"map":"Clubteacher","related":1] as NSDictionary
        NetWorkMngTool.sharedNetworkMngtool().Network_GetClubTeacherList(parameters, view: self.view){(videoList) in
            self.teacherList = videoList
            self.tableView.reloadData()
        }
        
    }
    func getCourse(){
        let parameters = ["mod":"club","SessionID":"2ul9sj8vlfofj122e1s98048k2","id":Club.id,"map":"Clubcourse","related":1] as NSDictionary
        NetWorkMngTool.sharedNetworkMngtool().Network_GetClubCourseList(parameters, view: self.view){(videoList) in
            self.courseList = videoList
            self.tableView.reloadData()
        }
        
    }
    
    func PlayVideo(sender:UIButton){
        
        let model = videosList[sender.tag] as! ClubVideoModel
        let str = "http://172.24.10.175/workout/Uploads/tvideo/video/" + (model.videopath! as String)
        print("路径：http://172.24.10.175/workout/Uploads/tvideo/video/\(model.videopath!)")
        self.performSegue(withIdentifier: "ToPlayVideo", sender: str)
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let Controller:PlayVideoViewController = segue.destination as! PlayVideoViewController
        Controller.str = sender as! String
    }
    
    func ToTeacherDetail(sender:UIButton){
        
    }
    func ToCourseDetail(sender:UIButton){
        
    }
    func CreatFootView(){
        let footerView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 60))
        let footButton:UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: width, height: 60))
        footButton.setTitle("加入俱乐部", for: .normal)
        footButton.setTitleColor(UIColor.white, for: .normal)
        footButton.backgroundColor = UIColor.orange
        footButton.addTarget(self, action: #selector(AddClub), for: .touchUpInside)
        footerView.addSubview(footButton)
        tableView.tableFooterView = footerView
        
    }


}
